const {app} = require('electron')

/**
 * 连接指定webviewId的webview
 * @returns {Promise<void>}
 */
module.exports = async function (webviewId, cookiesArray) {
    console.log('准备连接webview:', webviewId)
   const browser = app.puppeteer
   const targets = await browser.targets()
   for (const target of targets) {
        if (target.type() === 'webview') {
            // 如果当前目标是 webview 则判断是否是匹配的 webview
            let page = await target.page()
            let webviewIdInPage = await page.evaluate(() => localStorage.getItem("webviewId"))
            if (webviewIdInPage === webviewId) {
                console.log(`找到了【${webviewId}】对应的webview:`)
                if (cookiesArray) {
                    await page.setCookie(...cookiesArray)
                }
                return page
            }
        }
   }
   return null;
}
